package com.yn.module.material.utils.xls;

import com.yn.common.utils.ex.BusinessException;
import com.yn.module.material.utils.ErrorCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @description: 需要注入才能使用的Excel校验工具类
 * @author: zq
 * @create: 2022/3/29 14:20
 * @since: 1.0.0
 * @copyright (C), 2020, 北京望海康信科技有限公司.All rights reserved.
 */
@Component
@RequiredArgsConstructor
public class ExcelCheckUtils {
    private final Validator validator;

    /**
     * 参见：StdDiagnosisService#checkExcel(int, com.viewhigh.data.mc.web.cost.dto.excel.ExcelInfo, List)
     *  StdMaterialService#checkExcel(int, com.viewhigh.data.mc.web.cost.dto.excel.ExcelInfo, List)
     * @param errList          业务校验错误信息存储的列表
     * @param uniqueCheckedSet 如果需要进行当前列表中唯一值校验时，不允许为空
     * @param ec
     */
    public void validatedExcelLineData(List<String> errList, Set<String> uniqueCheckedSet, ExcelCheck ec) {
        Set<ConstraintViolation<Object>> validators = validator.validate(ec.item());
        if (validators != null && validators.size() > 0) {
            for (ConstraintViolation<Object> model : validators) {
                errList.add(model.getMessage());
            }
            if (ec.data() != null && !"".equals(ec.data())) {
                if (uniqueCheckedSet == null) uniqueCheckedSet = new HashSet<>();
                if (uniqueCheckedSet.contains(ec.data())) {
                    errList.add(ec.dataErrMsg());
                }
                uniqueCheckedSet.add(ec.data());
            }
        }
        if (errList != null && errList.size() > 0)
            throw new BusinessException(ErrorCode.xls_check_err.getCode(), String.format("原始数据共%d行，第%d行校验失败。错误信息：%s",
                    ec.length() + ec.headLines(), ec.current() + ec.headLines() + 1, String.join(";", errList)));
    }
}
